import datetime
import sys

DEBUG = "DEBUG"
INFO = "INFO"
WARN = "WARN"
ERROR = "ERROR"

FMT_DATETIME = '%Y-%m-%d %H:%M:%S'


class Logger:
    TAG = {
        DEBUG: 4,
        INFO: 3,
        WARN: 2,
        ERROR: 1
    }

    def __init__(self, sender):
        self.set_sender(sender)
        self.set_level(INFO)
        self.set_file(sys.stdout)

    def set_level(self, level):
        self._level = level

    def set_sender(self, sender):
        self._sender = sender

    def set_file(self, file):
        self._file = file

    def _log(self, level, message):
        if self.TAG[level] <= self.TAG[self._level]:
            self._file.write("%s %s - %s: %s\n" % (datetime.datetime.now().strftime(FMT_DATETIME),
                                                   level,
                                                   self._sender,
                                                   message))
            self._file.flush()

    def debug(self, message):
        self._log(DEBUG, message)

    def info(self, message):
        self._log(INFO, message)

    def warn(self, message):
        self._log(WARN, message)

    def error(self, message):
        self._log(ERROR, message)


def get_logger(cls):
    logger = Logger(cls)
    from . import config
    if 'file' in config.logger:
        logger.set_file(open(config.logger['file']))
    if 'log_level' in config.logger:
        logger.set_level(config.logger['log_level'])
    return logger
